package initialize

import (
	"MxShopApi/global"
	"MxShopApi/proto"
	"fmt"
	"github.com/hashicorp/consul/api"
	_ "github.com/mbobakov/grpc-consul-resolver"
	"github.com/spf13/viper"
	"go.uber.org/zap"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials/insecure"
)

func GetEnvInfo(env string) bool {
	viper.AutomaticEnv()
	return viper.GetBool(env)
	//刚才设置的环境变量 想要生效 我们必须得重启goland
}

func InitSrvConfig() {
	config := api.DefaultConfig()
	debug := GetEnvInfo("MXSHOP_DEBUG")
	configFilePrefix := "config"
	configFileName := fmt.Sprintf("/Users/fuyx/GolandProjects/gin_grpc_project/GinTest_api/%s_dev.yaml", configFilePrefix)
	if debug {
		configFileName = fmt.Sprintf("/Users/fuyx/GolandProjects/gin_grpc_project/GinTest_api/%s_pro.yaml", configFilePrefix)
	}
	//读取配置文件
	v := viper.New()
	//v.SetConfigName("config_dev")
	//v.SetConfigFile("/Users/fuyx/GolandProjects/gin_grpc_project/GinTest_api/")
	//v.SetConfigType("yaml")
	//文件的路径如何设置
	v.SetConfigFile(configFileName)
	v.SetConfigFile("/Users/fuyx/GolandProjects/gin_grpc_project/GinTest_api/config_dev.yaml")
	if err := v.ReadInConfig(); err != nil {
		panic(err)
	}
	//把读取到的配置信息和配置结构体映射
	serverConfig := global.ServerConfig
	if err := v.Unmarshal(&serverConfig); err != nil {
		panic(err)
	}
	consulInfo := global.ServerConfig.ConsulInfo
	config.Address = fmt.Sprintf("%s:%d", consulInfo.Host, consulInfo.Port)
	userSrvHost := ""
	userSrvPort := 0
	client, err := api.NewClient(config)
	if err != nil {
		panic(err)
	}
	//服务过滤（要哪个用哪个）
	data, err := client.Agent().ServicesWithFilter(fmt.Sprintf("Service == \"%s\"", global.ServerConfig.OrderSrvInfo.Name))
	if err != nil {
		panic(err)
	}

	//获取rpc服务的host和port
	for _, value := range data {
		userSrvHost = value.Address
		userSrvPort = value.Port
		break
	}

	//判断rpc服务是否存在
	if userSrvHost == "" {
		zap.S().Fatal("用户rpc服务不存在")
		return
	}

	//API和RPC服务的连接
	userClient, err := grpc.Dial(fmt.Sprintf("%s:%d", userSrvHost, userSrvPort),
		grpc.WithTransportCredentials(insecure.NewCredentials()))
	userSrvClient := proto.NewUserClient(userClient)
	global.UserSrvClient = userSrvClient
}

func InitSrvConfigs() {
	consulInfo := global.ServerConfig.ConsulInfo
	userConn, err := grpc.Dial(fmt.Sprintf("consul://%s:%d/%s?wait=14s", consulInfo.Host, consulInfo.Port, global.ServerConfig.OrderSrvInfo.Name),
		grpc.WithInsecure(),
		grpc.WithDefaultServiceConfig(`{"loadBalancingPolicy": "round_robin"}`),
	)
	if err != nil {
		zap.S().Fatal("用户服务连接失败")
	}
	userSrvClient := proto.NewUserClient(userConn)
	global.UserSrvClient = userSrvClient
}
